package com.itheima.pay.wechat;

import com.alipay.api.internal.util.file.IOUtils;
import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @authar by xiecong
 * @Date 2022/4/11
 * @Description
 */
@Slf4j
@RestController
@RequestMapping("/wechat")
public class WeChatPayController {

    //加载微信配置
    @Autowired
    WXPayConfigCustom wxPayConfigCustom;

    /**
     * 支付回调通知
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/notify")
    public String payNotify(HttpServletRequest request, HttpServletResponse response) {
        try {
            String xmlResult = IOUtils.toString(request.getInputStream(), request.getCharacterEncoding());
            Map<String, String> map = WXPayUtil.xmlToMap(xmlResult);
            // 加入自己处理订单的业务逻辑，需要判断订单是否已经支付过，否则可能会重复调用
            String orderId = map.get("out_trade_no");
            String tradeNo = map.get("transaction_id");
            String totalFee = map.get("total_fee");
            String returnCode = map.get("return_code");
            String resultCode = map.get("result_code");
            return "OK";
        } catch (Exception e) {
//                log.error("微信回调结果异常,异常原因{}", e.getMessage());
            return "ERROR";
        }
    }

    /**
     * 下单生成二维码，下单
     *
     * @param out_trade_no
     */
    @GetMapping("/precreate/{out_trade_no}")
    public Map<String, String> precreate(@PathVariable("out_trade_no") String out_trade_no) {
        try {
            //初始化微信pay
            WXPay wxPay = new WXPay(wxPayConfigCustom);
            //封装参数到map中
            Map<String, String> map = new HashMap<>();
            map.put("body", "黑马餐饮-消费");
            map.put("out_trade_no", out_trade_no);
            map.put("total_fee", "10");//单位：分
            map.put("spbill_create_ip", "123.12.12.123");
            map.put("notify_url", "http://127.0.0.1:8080/wechat/notify");//微信回调url,使用内网穿透：http://127.0.0.1:8080
            map.put("trade_type", "NATIVE");
            //发起http远程调用
            Map<String, String> repData = wxPay.unifiedOrder(map);
            return repData;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 查看订单
     *
     * @param out_trade_no
     * @return
     */
    @GetMapping("/query/{out_trade_no}")
    public Map<String, String> query(@PathVariable("out_trade_no") String out_trade_no) {
        //初始化微信pay
        try {
            WXPay wxPay = new WXPay(wxPayConfigCustom);
            //封装参数到map中
            Map<String, String> map = new HashMap<>();
            map.put("out_trade_no", out_trade_no);
            //发起http远程调用
            Map<String, String> repData = wxPay.orderQuery(map);
            //交易成功判断条件： return_code、result_code和trade_state都为SUCCESS
            String return_code = repData.get("return_code");
            String result_code = repData.get("result_code");
            String trade_state = repData.get("trade_state");
            //判断
            if ("SUCCESS".equals(return_code) && "SUCCESS".equals(result_code) && "SUCCESS".equals(trade_state)) {
                //成功
            }
            return repData;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 退款
     *
     * @param out_trade_no
     * @param out_refund_no
     * @return
     */
    @GetMapping("/refund/{out_trade_no}")
    public Map<String, String> refund(@PathVariable("out_trade_no") String out_trade_no,
                                      @PathVariable("out_refund_no") String out_refund_no) {
        try {
            WXPay wxPay = new WXPay(wxPayConfigCustom);
            //封装参数到map中
            Map<String, String> map = new HashMap<>();
            map.put("out_trade_no", out_trade_no);
            map.put("out_refund_no", out_trade_no);
            map.put("total_fee", "10");//订单金额
            map.put("refund_fee", "10");//退款金额
            //发起http远程调用
            Map<String, String> repData = wxPay.refund(map);
            return repData;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 查看退款
     * @param out_trade_no
     * @param out_request_no
     */
    @GetMapping("/refundquery/{out_trade_no}/{out_request_no}")
    public void refundquery(@PathVariable("out_trade_no") String out_trade_no,
                            @PathVariable("out_request_no") String out_request_no) {

    }
}
